package repository

import (
	"bytes"
	"strconv"

	"gitee.com/yyzh999/message/internal/pkg/config"
	"gitee.com/yyzh999/message/internal/pkg/logger"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var db *gorm.DB

func init() {
	connectDb()
}

func connectDb() error {

	var buffer bytes.Buffer
	buffer.WriteString(config.GetDbUserName())
	buffer.WriteString(":")
	buffer.WriteString(config.GetDbPassword())
	buffer.WriteString("@tcp(")
	buffer.WriteString(config.GetDbHost())
	buffer.WriteString(":")
	buffer.WriteString(strconv.Itoa(int(config.GetDbPort())))
	buffer.WriteString(")/")
	buffer.WriteString(config.GetDbDatabase())
	buffer.WriteString("?charset=utf8mb4&parseTime=True&loc=Local")

	dsn := buffer.String()
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	if err != nil {
		logger.DPanicSf("数据库连接失败:%v", err)
	}

	return nil
}
